package com.lovo.service.impl;

import com.lovo.dao.BaseDAO;
import com.lovo.dao.UserDAO;
import com.lovo.dao.impl.UserDAOImpl;
import com.lovo.pojo.UserDO;
import com.lovo.service.UserService;

public class UserServiceImpl implements UserService {
    private UserDAO userDAO = new UserDAOImpl();
    private BaseDAO baseDAO = new UserDAOImpl();

    @Override
    public UserDO getByUsernameAndPwd(String username, String pwd) {
        return userDAO.getByUsernameAndPwd(username, pwd);
    }

    @Override
    public void saveMoney(int id, double balance) {
        UserDO user = userDAO.getById(id);
        user.setBalance(user.getBalance() + balance);
        userDAO.update(user);
    }

    @Override
    public void getMoney(int id, double balance) throws Exception {
        UserDO user = userDAO.getById(id);
        if (user.getBalance() < balance) {
            throw new Exception("余额不足");
        }
        user.setBalance(user.getBalance() - balance);
        userDAO.update(user);
    }

    @Override
    public void transferMoney(int id, String username, double balance) throws Exception {
        UserDO loginUser = userDAO.getById(id);
        UserDO otherUser = userDAO.getByUsername(username);
        // 判断账号是否存在
        if (otherUser == null) {
            throw new Exception("查无此人");
        }
        // 判断是否转给自己
        if (loginUser.getAccount().equals(username)) {
            throw new Exception("不能转给自己");
        }
        // 判断余额是否足够
        if (balance > loginUser.getBalance()) {
            throw new Exception("余额不足");
        }

        // 当前账户扣钱
        loginUser.setBalance(loginUser.getBalance() - balance);
        // 对方账户加钱
        otherUser.setBalance(otherUser.getBalance() + balance);
        userDAO.update(loginUser);
        userDAO.update(otherUser);

    }

    @Override
    public void register(String username, String pwd, String ConfirmPwd) throws Exception {
        UserDO user = userDAO.getByUsername(username);
        //判断账户是否已经存在
        if (user != null) {
            throw new Exception("账号已存在");
        }
        // 判断两次输入的密码是否相同
        if (!pwd.equals(ConfirmPwd)) {
            throw new Exception("两次密码不一致");
        }
        //更新到用户表及其数据库
        UserDO newUser = new UserDO(username, pwd, 0);
        userDAO.insert(newUser);
    }


}
